package jp.dev7.android.util;

import java.net.URI;

import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.HttpParams;

import android.net.http.AndroidHttpClient;
import android.util.Log;
import android.widget.ProgressBar;

public abstract class AbstractDownloadWorker<T> extends AbstractWorker<T> {

	protected ProgressBar progressBar;
	private URI uri;

	public AbstractDownloadWorker(ProgressBar progressBar, URI uri) {
		super();
		this.progressBar = progressBar;
		this.uri = uri;
	}

	public AbstractDownloadWorker(ProgressBar progressBar, String uri) {
		this(progressBar, URI.create(uri));
	}

	@Override
	protected T doInBackground() throws Throwable {
		if (progressBar != null) {
			progressBar.setIndeterminate(true);
		}

		AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
		try {

			HttpGet request = createRequest();

			Log.i(getClass().toString(), uri + "との通信開始");
			HttpResponse response = httpClient.execute(request);
			Log.i(getClass().toString(), uri + "との通信正常終了");

			if (progressBar != null) {
				progressBar.setIndeterminate(false);
			}

			StatusLine status = response.getStatusLine();
			if (status.getStatusCode() != HttpStatus.SC_OK) {
				throw new HttpException(status.getStatusCode() + " "
						+ status.getReasonPhrase());
			}

			return parseResponse(response);

		} finally {
			httpClient.close();
		}
	}

	protected HttpGet createRequest() throws Throwable {
		HttpGet request = new HttpGet(uri);

		Header header = requestHeader();
		if (header != null) {
			request.setHeader(header);
		}
		HttpParams param = requestParameter();
		if (param != null) {
			request.setParams(param);
		}
		return request;
	}

	protected Header requestHeader() throws Throwable {
		return null;
	}

	protected HttpParams requestParameter() throws Throwable {
		return null;
	}

	protected T parseResponse(HttpResponse response) throws Throwable {
		return null;
	}

}
